﻿namespace ImageDupFinder.ProgramCore
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    /// <summary>
    /// Util class for accesing values using two indexes
    /// </summary>
    /// <typeparam name="TKey">The type of keys</typeparam>
    /// <typeparam name="TValue">The type of elements in array</typeparam>
    public class TriangleDictionary<TKey, TValue> : Dictionary<TKey, Dictionary<TKey, TValue>>
    {
        // TODO provide proper implementation for TriangleDictionary class

        /// <summary>
        /// Get or set value associated with keypair
        /// </summary>
        /// <param name="key1">First key of keypair</param>
        /// <param name="key2">Second key of keypair</param>
        /// <returns>value associated with keypair</returns>
        public TValue this[TKey key1, TKey key2]
        {
            get
            {
                TValue v;
                if (this[key1].TryGetValue(key2, out v))
                {
                    return v;
                }
                else
                {
                    return this[key2][key1];
                }
            }

            set
            {
                if (this[key1].Count > this[key2].Count)
                {
                    this[key1][key2] = value;
                }
                else
                {
                    this[key2][key1] = value;
                }
            }
        }

        /// <summary>
        /// Remove the value with the specified key from main dictionary and all subdictionaries
        /// </summary>
        /// <param name="key">Key to be removed</param>
        public new void Remove(TKey key)
        {
            base.Remove(key);
            foreach (Dictionary<TKey, TValue> d in this.Values)
            {
                d.Remove(key);
            }
        }

        /// <summary>
        /// Remove value associated with keypair
        /// </summary>
        /// <param name="key1">First key of keypair</param>
        /// <param name="key2">Second key of keypair</param>
        public void RemoveValue(TKey key1, TKey key2)
        {
            // try remove in both subdictionaries
            this[key1].Remove(key2);
            this[key2].Remove(key1);
        }
    }
}
